<template>
    <view class="wish-wall-container">
        <view @click="handleOpenWishModal(lantern)" v-for="(lantern, index) in lanterns" class="lantern" :key="index"
            :style="{
                left: `${lantern.left}%`,
                top: `${lantern.top}%`,
                width: `${lantern.size}rpx`,
                height: 'auto',
                zIndex: lantern.zIndex,
                opacity: lantern.opacity
            }">
            <image class="lantern-image" :src="light_image" mode="widthFix" />
        </view>
        <view @click="handleOpenWishModal(wishListLatest)" class="center-lantern">
            <image class="lantern-image" :src="light_image" mode="widthFix" />
        </view>
    </view>
    <WishModal :wish="currentWish" readonly v-model:show="wishModalShow" />
</template>

<script setup lang="ts">
    import { ref, watch, computed } from 'vue';
    import light_image from "/static/assets/images/blessings/light.png";
    import { useWishStore } from '@/stores/wish';
    import WishModal from '../../WishModal/WishModal.vue'

    const wishModalShow = ref(false);
    const wishStore = useWishStore();
    const wishList = computed(() => {
        return wishStore.wishList?.slice(1);
    });

    const wishListLatest = computed(() => {
        return wishStore.wishList?.[0] || {};
    });

    const currentWish = ref({})
    const lanterns = ref([]);

    const handleOpenWishModal = (item) => {
        currentWish.value = item;
        wishModalShow.value = true;
    }

    // 生成随机位置，避免重叠
    const generateNonOverlappingPosition = (size, existingLanterns) => {
        const maxAttempts = 50; // 最大尝试次数
        let attempt = 0;

        // 计算灯笼实际占用的空间（百分比）
        // 将rpx转换为百分比空间的近似值
        const sizeInPercent = size / 7.5; // 估算rpx到百分比的转换

        // 计算灯笼的高度（基于36:43的宽高比）
        const heightInPercent = (sizeInPercent * 43) / 36;

        // 定义容器边界，考虑灯笼完整尺寸
        const minX = sizeInPercent / 2;
        const maxX = 100 - sizeInPercent / 2;
        const minY = heightInPercent / 2;
        const maxY = 100 - heightInPercent / 2;

        // 定义中心区域的范围
        const centerX = 50;
        const centerY = 50;
        const centerSize = 30; // 中心区域大小（百分比）

        while (attempt < maxAttempts) {
            attempt++;

            // 生成随机位置
            let left = minX + Math.random() * (maxX - minX);
            let top = minY + Math.random() * (maxY - minY);

            // 检查是否在中心区域
            const distanceToCenter = Math.sqrt(
                Math.pow(left - centerX, 2) +
                Math.pow(top - centerY, 2)
            );
            if (distanceToCenter < centerSize) {
                continue; // 如果在中心区域，重新生成
            }

            // 检查是否与现有灯笼重叠
            let overlaps = false;
            for (const lantern of existingLanterns) {
                const dx = Math.abs(left - lantern.left);
                const dy = Math.abs(top - lantern.top);
                const minDistance = (sizeInPercent + lantern.size / 7.5) / 2;

                if (dx < minDistance && dy < minDistance) {
                    overlaps = true;
                    break;
                }
            }

            if (!overlaps) {
                return { left, top };
            }
        }

        // 如果找不到合适的位置，返回一个备选位置
        const corners = [
            { left: minX, top: minY }, // 左上
            { left: maxX, top: minY }, // 右上
            { left: minX, top: maxY }, // 左下
            { left: maxX, top: maxY }  // 右下
        ];
        return corners[Math.floor(Math.random() * corners.length)];
    };

    const generateLanterns = () => {
        const lanternsList = [];
        wishList.value.forEach((item, index) => {
            const size = 160 + Math.random() * 70;
            const position = generateNonOverlappingPosition(size, lanternsList);
            lanternsList.push({
                ...item,
                size,
                left: position.left,
                top: position.top,
                zIndex: index + 10,
                opacity: 0.8 + Math.random() * 0.2 // 0.8-1.0透明度
            })
        })
        lanterns.value = lanternsList;
    };

    watch(() => wishList.value, () => {
        generateLanterns();
    }, {
        immediate: true
    });
</script>

<style lang="less" scoped>
    .wish-wall-container {
        position: relative;
        height: calc(100vh - var(--navbar-height) - var(--window-bottom) - var(--status-bar-height) - var(--tabbar-height));
        width: 100%;
        overflow: hidden;
    }

    .lantern {
        position: absolute;
        animation: float 3s ease-in-out infinite;
    }

    .center-lantern {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -25%);
        width: 575rpx;
        height: auto;
        z-index: 1;
    }

    .lantern-image {
        width: 100%;
    }

    @keyframes float {

        0%,
        100% {
            transform: translate(0, 0);
        }

        50% {
            transform: translate(0, 4%);
        }
    }
</style>